﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Collections.Generic;

using Patterns.Collections;

namespace Patterns.Cache
{
	/// <summary>
	/// 	Provides a message "hub" for cache events.
	/// </summary>
	public class CacheEventMessenger
	{
		/// <summary>
		/// The update message handlers.
		/// </summary>
		protected readonly IDictionary<string, ICollection<Action<CacheEvent>>> _updateHandlers
			= new Dictionary<string, ICollection<Action<CacheEvent>>>(StringComparer.OrdinalIgnoreCase);

		/// <summary>
		/// Adds the recipient.
		/// </summary>
		/// <param name="itemKey">The item key.</param>
		/// <param name="handler">The handler.</param>
		public virtual void AddRecipient(string itemKey, Action<CacheEvent> handler)
		{
			ICollection<Action<CacheEvent>> handlers = _updateHandlers[itemKey] ?? new List<Action<CacheEvent>>();
			handlers.Add(handler);
			_updateHandlers[itemKey] = handlers;
		}

		/// <summary>
		/// Sends the messages.
		/// </summary>
		/// <param name="itemKey">The item key.</param>
		/// <param name="item">The item.</param>
		/// <param name="eventType">Type of the event.</param>
		/// <param name="parallel">if set to <c>true</c> run in parallel.</param>
		public virtual void SendMessages(string itemKey, object item, CacheEventType eventType, bool parallel)
		{
			ICollection<Action<CacheEvent>> handlers = _updateHandlers.GetValue(itemKey);
			if (handlers != null) handlers.ForEach(handler => handler(new CacheEvent { Key = itemKey, Data = item, EventType = eventType }), parallel);
		}
	}
}